package com.AndroidExplorer;

import java.io.*;
import java.net.*;
import java.util.*;

import android.app.*;
import android.content.*;
import android.graphics.*;
import android.media.*;
import android.os.*;
import android.util.*;
import android.view.*;
import android.widget.*;

public class AndroidExplorer extends ListActivity {
	
	static final int ID_JPGDIALOG = 0;
	private static final int CONNECT_TIMEOUT = 60 * 1000;
	private static final int READ_TIMEOUT = 60 * 1000;
	private static final int RETRY_COUNT = 3;
	
	String filename;
	String exifAttribute;
	TextView exifText;
	TextView geoText;
	ImageView bmImage;
	BitmapFactory.Options bmOptions; 
	File jpgFile;
	Dialog jpgDialog;
	Button mapviewButton;
	
	geoDegree myGeoDegree;
	
	private List<String> item = null;
	private List<String> path = null;
	private String root="/";
	private TextView myPath;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        myPath = (TextView)findViewById(R.id.path);
        getDir(root);
    }
    
    private void getDir(String dirPath)
    {
    	myPath.setText("Location: " + dirPath);
    	
    	item = new ArrayList<String>();
    	path = new ArrayList<String>();
    	
    	File f = new File(dirPath);
    	File[] files = f.listFiles();
    	if(!dirPath.equals(root))
    	{

    		item.add(root);
    		path.add(root);
    		
    		item.add("../");
    		path.add(f.getParent());
            
    	}
    	
    	for(int i=0; i < files.length; i++)
    	{
    			File file = files[i];
    			path.add(file.getPath());
    			if(file.isDirectory())
    				item.add(file.getName() + "/");
    			else
    				item.add(file.getName());
    	}

    	ArrayAdapter<String> fileList =
    		new ArrayAdapter<String>(this, R.layout.row, item);
    	setListAdapter(fileList);
    }
    

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		
		File file = new File(path.get(position));
//		File file = new File("content://media/external/images/media/67");
		
		Log.e("", "path ::: "+path.get(position));
		if (file.isDirectory())
		{
			if(file.canRead())
				getDir(path.get(position));
			else
			{
				new AlertDialog.Builder(this)
				.setIcon(R.drawable.icon)
				.setTitle("[" + file.getName() + "] folder can't be read!")
				.setPositiveButton("OK", 
						new DialogInterface.OnClickListener() {
							
							public void onClick(DialogInterface dialog, int which) {
								// TODO Auto-generated method stub
							}
						}).show();
			}
		}
		else
		{
			
//			postFiles(file);
//			connectUrlGet("");
//			connectUrlPost("");
//			List<String> names=new ArrayList<String>();
//			List<String> values=new ArrayList<String>();
//			names.add("param1");
//			names.add("param2");
//			names.add("param3");
//			values.add("value1");
//			values.add("value2");
//			values.add("value3");
//			connectUrlPost("" ,names,values, path);
			exifAttribute = null;
			filename = file.getName();
			String ext = filename.substring(filename.lastIndexOf('.')+1, filename.length());
			Log.e("", "fileLength :: "+file.length());
			if(ext.equals("JPG")||ext.equals("jpg"))
			{	ExifInterface exif;
				try {
					exif = new ExifInterface(file.toString());
					exifAttribute = getExif(exif);
					myGeoDegree = new geoDegree(exif);
					//showGeoInfo(exif);
					
				} catch (IOException e) {
					// TODO Auto-generated catch block
					;
				}
				jpgFile = file;
				showDialog(ID_JPGDIALOG);
			}
			else{
				new AlertDialog.Builder(this)
			    .setIcon(R.drawable.icon)
			    .setTitle("[" + filename + "]")
			    .setMessage(exifAttribute)
			    .setPositiveButton("OK", 
			      new DialogInterface.OnClickListener() {
			       
			       public void onClick(DialogInterface dialog, int which) {
			        // TODO Auto-generated method stub
			       }
			      }).show();
			}
		}
	}
	
    private String getExif(ExifInterface exif)
    {
     String myAttribute="";
     myAttribute += getTagString(ExifInterface.TAG_DATETIME, exif);
     myAttribute += getTagString(ExifInterface.TAG_FLASH, exif);
     myAttribute += getTagString(ExifInterface.TAG_GPS_LATITUDE, exif);
     myAttribute += getTagString(ExifInterface.TAG_GPS_LATITUDE_REF, exif);
     myAttribute += getTagString(ExifInterface.TAG_GPS_LONGITUDE, exif);
     myAttribute += getTagString(ExifInterface.TAG_GPS_LONGITUDE_REF, exif);
     myAttribute += getTagString(ExifInterface.TAG_IMAGE_LENGTH, exif);
     myAttribute += getTagString(ExifInterface.TAG_IMAGE_WIDTH, exif);
     myAttribute += getTagString(ExifInterface.TAG_MAKE, exif);
     myAttribute += getTagString(ExifInterface.TAG_MODEL, exif);
     myAttribute += getTagString(ExifInterface.TAG_ORIENTATION, exif);
     myAttribute += getTagString(ExifInterface.TAG_WHITE_BALANCE, exif);
     Log.e("", "myAttribute>>"+myAttribute);
     return myAttribute;
    }
    
    private String getTagString(String tag, ExifInterface exif)
    {
     return(tag + " : " + exif.getAttribute(tag) + "\n");
    }

	@Override
	protected Dialog onCreateDialog(int id) {
		jpgDialog = null;;
		switch(id){
		case ID_JPGDIALOG:

			Context mContext = this;
			jpgDialog = new Dialog(mContext);

			jpgDialog.setContentView(R.layout.jpgdialog);
			exifText = (TextView) jpgDialog.findViewById(R.id.text);
			
			geoText = (TextView)jpgDialog.findViewById(R.id.geotext);
			
			bmImage = (ImageView)jpgDialog.findViewById(R.id.image);
			bmOptions = new BitmapFactory.Options();
			bmOptions.inSampleSize = 2;
			
			Button okDialogButton = (Button)jpgDialog.findViewById(R.id.okdialogbutton);
			okDialogButton.setOnClickListener(okDialogButtonOnClickListener);
			mapviewButton = (Button)jpgDialog.findViewById(R.id.mapviewbutton);
			mapviewButton.setOnClickListener(mapviewButtonOnClickListener);
			
			break;
		default:
			break;
		}
		return jpgDialog;
	}

	@Override
	protected void onPrepareDialog(int id, Dialog dialog) {
		// TODO Auto-generated method stub

		switch(id){
		case ID_JPGDIALOG:
			dialog.setTitle("[" + filename + "]");
			exifText.setText(exifAttribute);
			Bitmap bm = BitmapFactory.decodeFile(jpgFile.getPath(), bmOptions);
			bmImage.setImageBitmap(bm); 
			
			if(myGeoDegree.isValid())
			{
				geoText.setText(myGeoDegree.toString());
				mapviewButton.setClickable(true);
				mapviewButton.setVisibility(View.VISIBLE);
			}
			else
			{
				geoText.setText("");
				mapviewButton.setClickable(false);
				mapviewButton.setVisibility(View.GONE);
			}
			break;
		default:
			break;
		}
	}
    
	private Button.OnClickListener okDialogButtonOnClickListener
		= new Button.OnClickListener(){

			public void onClick(View v) {
				// TODO Auto-generated method stub
				jpgDialog.dismiss();
			}
	};
	
	private Button.OnClickListener mapviewButtonOnClickListener
		= new Button.OnClickListener(){

			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				StartMapView();
			}
	};
	
	private void StartMapView(){
		Intent intent = new Intent();
		intent.setClass(AndroidExplorer.this, AndroidExplorerMapView.class);
		Bundle bundle = new Bundle();
		bundle.putInt("Longitude", myGeoDegree.getLongitudeE6());
		bundle.putInt("Latitude", myGeoDegree.getLatitudeE6());
		intent.putExtras(bundle);
		startActivity(intent);
	}
	
	public void connectUrlPost(String httpUrl) {
//		Log.e("Http", httpUrl);
		String serverUrl = "";
		httpUrl = "http://172.20.49.101:8080/Test/testReceive.jsp?tt='ggg'&hh='kkk'";
		StringBuffer body = new StringBuffer();
		try {
			int pos = httpUrl.indexOf((String) ("?"));
			String param = "";
			if (pos != -1) {
				serverUrl = httpUrl.substring(0, pos);
				param = httpUrl.substring(pos + 1);
			}
			String[] params = param.split("&");
			for (int i = 0; i < params.length; i++) {
				final String keyvalue = params[i];
				int po = keyvalue.indexOf((String) ("="));
				if (param.length() > po + 1)
					body.append("&" + keyvalue.substring(0, po) + "=" + URLEncoder.encode(new String(keyvalue.substring(po + 1).getBytes("euc-kr"), "8859_1")));
				else
					body.append("&" + keyvalue.substring(0, po) + "=");
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		HttpURLConnection conn = null;
		System.setProperty("http.keepAlive", "true");
		try {
			URL url = new URL(serverUrl);
			conn = (HttpURLConnection) url.openConnection();
			conn.setConnectTimeout(CONNECT_TIMEOUT);
			conn.setReadTimeout(READ_TIMEOUT);
			conn.setRequestMethod("POST");
			conn.setRequestProperty("Cache-Control", "no-cache");
		    String lineEnd = "\r\n";
		    String twoHyphens = "--";
		    String boundary = "*****";
			conn.setRequestProperty("Connection", "Keep-Alive");			
			conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
			conn.setDoOutput(true);
			conn.setDoInput(true);
			int responseCode = 0;
			OutputStream os = null;

			InputStream is = null;
			os = conn.getOutputStream();
			os.write(body.toString().getBytes());
			os.flush();
			responseCode = conn.getResponseCode();
			if (responseCode == HttpURLConnection.HTTP_OK) {
				is = conn.getInputStream();
				for (int i = 0; i < RETRY_COUNT; i++) {
					try {
//						htmlParse(is);
						break;
					} catch (Exception e) {
						e.printStackTrace();
						SystemClock.sleep(1000);
					}
				}
			}
			os.close();
			is.close();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (ProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			conn.disconnect();
		}

	}
	
	
	public void connectUrlGet(String urlHttp) {
		try {
			urlHttp = "http://172.20.49.101:8080/Test/testReceive.jsp?tt='ggg'&hh='kkk'";
			URL url = new URL(urlHttp);
			URLConnection conn = url.openConnection();
			conn.setUseCaches(false);
			conn.setConnectTimeout(CONNECT_TIMEOUT);
			conn.connect();
			InputStream is = null;

			for (int i = 0; i < RETRY_COUNT; i++) {
				try {
					is = conn.getInputStream();
//					htmlParse( is );
					break;
				} catch (Exception e) {
					is.close();
					e.printStackTrace();
					SystemClock.sleep(1000);
				}
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	/**
	 * Url encoding (get방식)
	 * @param httpUrl
	 * @return
	 */
	public String encodeParam(String httpUrl){
		String url ="";
		StringBuffer body = new StringBuffer();
		try {
		int pos = httpUrl.indexOf("?");
//		int paramPos = httpUrl.indexOf("&");
		String param = "";
		if (pos != -1) {
			url = httpUrl.substring(0, pos);
			param = httpUrl.substring(pos + 1);			
			String[] params = param.split("&");
			for (int i = 0; i < params.length; i++) {
				final String keyvalue = params[i];
				if(!"".equals(keyvalue)){
					int po = keyvalue.indexOf((String) ("="));
					String divider = i<1?"?":"&";
					if (param.length() > po + 1)
						body.append(divider + keyvalue.substring(0, po) + "=" + URLEncoder.encode(new String(keyvalue.substring(po + 1).getBytes("euc-kr"), "8859_1")));
					else
						body.append(divider + keyvalue.substring(0, po) + "=");
				}
			}
			url+=body;	
		}else
			url = httpUrl;
		Log.e("", "url ::: "+url);
		Log.e("", "body ::: "+body);
	} catch (UnsupportedEncodingException e) {
		e.printStackTrace();
		url = httpUrl;
	}
		return url;
	}
	
	public void connectUrlPost(String httpUrl ,List<String> paramNames,List<String> paramValues,List<String> path) {
		
		ArrayList<File> files =new ArrayList<File>();
		for(int i=0; i<path.size();i++)
			files.add(new File(path.get(i).toString()));
		
		String serverUrl = "";
	    String lineEnd = "\r\n";
	    String twoHyphens = "--";
	    String boundary = "*****";
		int responseCode = 0;
		String responseMsg="";
		//임시 url
		httpUrl = "http://172.20.49.101:8080/Test/testReceive.jsp";
		
		HttpURLConnection conn = null;
		DataOutputStream dos = null;
		FileInputStream fis = null;
		//get방식 
//		serverUrl =encodeParam(httpUrl);
		serverUrl = httpUrl;
		try {

			URL url = new URL(serverUrl);
			conn = (HttpURLConnection) url.openConnection();
			conn.setConnectTimeout(CONNECT_TIMEOUT);
			conn.setReadTimeout(READ_TIMEOUT);
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setRequestMethod("POST");
			conn.setRequestProperty("Cache-Control", "no-cache");
			
			 
			conn.setRequestProperty("Connection", "Keep-Alive");			
			conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
			dos = new DataOutputStream( conn.getOutputStream() );
			int maxBufferSize=1024;
			int bytesAvailable=0;
			int bufferSize=0;
			byte[] buffer=null;
			int bytesRead =0;
			 
			 //param roof
			 for(int i =0; i<paramNames.size();i++){
				dos.writeBytes(twoHyphens + boundary + lineEnd); //필드 구분자 시작
				dos.writeBytes("Content-Disposition: form-data; name=\""+paramNames.get(i)+"\""+ lineEnd);
				dos.writeBytes(lineEnd);
//				dos.writeBytes(URLEncoder.encode(new String("안녕gggg하하하하gg".getBytes("euc-kr"), "8859_1")));
				dos.writeBytes(paramValues.get(i));
				dos.writeBytes(lineEnd);
				dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);//필드 구분자 끝
			 }
			 
			 //file roof				
			 for(int i =0; i<files.size();i++){
				//======================start			
//				fis  = new FileInputStream(files.get(files.size()-1));
				fis  = new FileInputStream(files.get(i));
				dos.writeBytes(twoHyphens + boundary + lineEnd);
				dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + files.get(i).getName() +"\""+ lineEnd);
				dos.writeBytes(lineEnd);
				
				bytesAvailable = fis.available();
				bufferSize = Math.min(bytesAvailable, maxBufferSize);
				buffer = new byte[bufferSize];
				// read file and write it into form...
				bytesRead = fis.read(buffer, 0, bufferSize);
				while (bytesRead > 0)
				{
				    dos.write(buffer, 0, bufferSize);
				    bytesAvailable = fis.available();
				    bufferSize = Math.min(bytesAvailable, maxBufferSize);
				    bytesRead = fis.read(buffer, 0, bufferSize);
				}
				// send multipart form data necesssary after file data...
				dos.writeBytes(lineEnd);
				dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
				//======================end
			 }
			
			dos.flush();
			responseCode = conn.getResponseCode();
			responseMsg = conn.getResponseMessage();
			if (responseCode == HttpURLConnection.HTTP_OK) {
//				is = conn.getInputStream();
				for (int i = 0; i < RETRY_COUNT; i++) {
					try {
//						htmlParse(is);
						break;
					} catch (Exception e) {
						e.printStackTrace();
						SystemClock.sleep(1000);
					}
				}
			}
			Log.e("","responseCode >>>>>>"+responseCode);
			Log.e("","responseMsg >>>>>>"+responseMsg);	
			if(fis!=null) fis.close();
			if(dos!=null) dos.close();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (ProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {

			if(conn!=null)	conn.disconnect();
		}

	}
}